package we3d.filter 
{
	import flash.display.BitmapData;
	import flash.filters.BlurFilter;
	import flash.filters.BitmapFilterQuality;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	import we3d.View3d;
	import we3d.Scene3d;
	import we3d.math.Vector3d;
	import we3d.core.transform.Transform3d;
	
	public class SLMotionBlur extends BackgroundFilter 
	{
		public function SLMotionBlur () {}
		
		public var blurX:Number=1;
		public var blurY:Number=1;
		public var blurPosition:Number=.1;
		public var blurRotation:Number=1;
		public var blurQuality:int=BitmapFilterQuality.LOW;
		public var p:Point=new Point(0,0);
		
		private var camspeed:Number=0;
		private var prevpos:Vector3d=new Vector3d();
		private var prevrot:Vector3d=new Vector3d();
		private var frameCounter:int=0;
		
		public override function initialize (view:View3d) :void {
			
			if(view.scene != null) {
				var tr:Transform3d = view.scene.cam.transform;
				
				prevpos.x = tr.x;
				prevpos.y = tr.y;
				prevpos.z = tr.z;
				
				prevrot.x = tr.rotationX;
				prevrot.y = tr.rotationY;
				prevrot.z = tr.rotationZ;
			}
		}
		
		public override function endFrame (view:View3d) :void {
			
			var we:Scene3d = view.scene;
			
			var tr:Transform3d = we.cam.transform;
			
			var camx:Number = tr.x;
			var camy:Number = tr.y;
			var camz:Number = tr.z;
			
			var dx:Number = camx - prevpos.x;
			var dy:Number = camy - prevpos.y;
			var dz:Number = camz - prevpos.z;
			
			var d:Number = Math.sqrt(dx*dx + dy*dy + dz*dz)*blurPosition;
			
			prevpos.x = camx;
			prevpos.y = camy;
			prevpos.z = camz;
			
			camx = tr.rotationX;
			camy = tr.rotationY;
			camz = tr.rotationZ;
			
			dx = camx - prevrot.x;
			dy = camy - prevrot.y;
			dz = camz - prevrot.z;
			
			prevrot.x = camx;
			prevrot.y = camy;
			prevrot.z = camz;
			
			d = Math.max(d, Math.sqrt(dx*dx + dy*dy + dz*dz)/Math.PI*180*blurRotation);
			
			if(d > 0) {
			
				var bx:Number = blurX * d;
				var by:Number = blurY * d;
				
				if(bx > .5 || by > .5) {
					
					var lyrs:Array;
					if(layers == null) {
						lyrs = view.allLayers;
					}else{
						lyrs = layers;
					}
					
					if(lyrs) {
						
						var bf:BlurFilter = new BlurFilter(Math.round(bx), Math.round(by), blurQuality);
						
						var L:int = lyrs.length;
						var i:int;
						var bmp:BitmapData;
						
						for(i=0; i<L; i++) {
							bmp = lyrs[i].bmp;
							bmp.applyFilter(bmp, bmp.rect, p, bf);
						}
					}
				}
			}
		}
		
		
	}
}